package com.fulu.game.bi.mysql.config;

import com.fulu.game.bi.mysql.properties.MultipleDatabaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Slf4j
@Configuration
@EnableConfigurationProperties (
        { MultipleDatabaseProperties.class })
@MapperScan (basePackages = { "com.fulu.game.bi.mysql.bi"},
        sqlSessionFactoryRef = "biDbSqlSessionFactory")
public class BiDbConfig extends AbstractDbConfig {

    @Autowired
    private MultipleDatabaseProperties multipleDatabaseProperties;

    @Bean(name = "biDbDataSource")
    @Primary
    public DataSource dataSource() {
        DataSourceProperties dbProperties = multipleDatabaseProperties.getBiDb();

        return getDruidDataSource(dbProperties);
    }

    @Bean(name = "biDbSqlSessionFactory")
    @Primary
    public SqlSessionFactory biDbSqlSessionFactory (@Qualifier("biDbDataSource") DataSource dataSource) throws Exception {
        String locationPattern = "classpath:META-INF/bi/mybatis/*.xml";

        return getSqlSessionFactory(dataSource, locationPattern);
    }

    @Bean (name = "biTransactionManager")
    @Primary
        public DataSourceTransactionManager biTransactionManager (@Qualifier ("biDbDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager (dataSource);
    }

    @Bean (name = "biDbSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate biDbSqlSessionTemplate (@Qualifier ("biDbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate (sqlSessionFactory);
    }
}
